#include <string.h>
#include <math.h>
#include "system.h"
#include "f1c100s_de.h"
#include "f1c100s_timer.h"
#include "f1c100s_intc.h"
#include "f1c100s_gpio.h"
#include "f1c100s_pwm.h"
#include "f1c100s_uart.h"
#include "arm32.h"
#include "time0.h"
#include "f1c100s_audio.h"
#include "f1c100s_dma.h"
#include "f1c100s_sdc.h"
#include "sd.h"
#include "sdcard.h"
#include "ff.h"
#include "diskio.h"
#include "fatfs.h"
#include "wav_io.h"
int main(void)
{
  system_init();            // Initialize clocks, mmu, cache, uart, ...
  arm32_interrupt_enable(); // Enable interrupts
  timer0_init();
  printf("\r\napp [AUDIO_WAV] run. compiled_time %s %s\r\n", __DATE__, __TIME__);
  delay(200);
  sdcard_init();
  fatfs_init();
  fatfs_test();
  f1c100s_audio_init();
  wav_head wav;
  uint8_t wavdat[32768];
  FIL fil;
  // test.wav 44100 16bit 2ch
  FRESULT ret = f_open(&fil, "test.wav", FA_READ | FA_OPEN_ALWAYS);
  if (ret == FR_OK)
  {
    uint32_t br;
    f_read(&fil, &wav, sizeof(wav_head), &br);
    wave_head_parse(&wav);
    f1c100s_audio_config(0, wav.audio_bit, wav.audio_sample_rate);
    f1c100s_audio_open(wav.audio_bps / 60);

    for (int i = 0; i < wav.audio_data_length / 32768; i++)
    {
      memset(wavdat, 0, sizeof(wavdat));
      f_lseek(&fil, i * 32768 + sizeof(wav_head));
      f_read(&fil, wavdat, 32768, &br);
      audio_pcm_play(wavdat, 32768); // wait dma over.
    }
    f_close(&fil);
  }
  else
  {
    printf("open file wav file fail %d.\r\n", ret);
  }

  while (1)
  {

    delay(1000);
  }
}
